/* eslint-disable no-undef */
import React, { Component, Fragment } from 'react'
import Editor from 'for-editor'
import marked from 'marked'
import BlogHeader from '../components/blog/BlogHeader'
import { withRouter } from 'react-router-dom'
// import 'qiniu-js/dist/qiniu.min.js';
import TitleInput from '../components/writeArticle/TitleInput'
import '../componentStyle/editArticlePage.scss'
import { _addArticle } from '../components/common/Api'
import { message } from 'antd';

const success = () => {
    message.success('增加文章成功');
  };

// let Qiniu;

class EditArticlePage extends Component {
    constructor() {
        super()
        this.state = {
            value: '',
            title: ''
        }
        this.$vm = React.createRef()
    }

    handleChange(value) {
        this.setState({
            value
        })
    }

    // 保存title的值
    saveTitle = (title) => {
        this.setState({
            title
        });
    }

    // 上传图片到七牛云
    initQiniu() {
        Qiniu.uploader({
            runtimes: 'html5,flash,html4',
            browse_button: 'uploadImage',
            flash_swf_url: 'https://cdn.bootcss.com/plupload/2.1.1/Moxie.swf',
            chunk_size: '4mb',
            uptoken: "vHg2e7nOh7Jsucv2Azr5FH6omPgX22zoJRWa0FN5:5kyaOpzFbn1Nr7Pq_gj3Aw87sAU=:eyJkZWxldGVBZnRlckRheXMiOjEsInNjb3BlIjoianNzZGsiLCJkZWFkbGluZSI6MTU4MDAzMjQxNn0=",
            // uptoken_url: 'http://jssdk.demo.qiniu.io/uptoken',
            domain: 'http://q44u5rtaq.bkt.clouddn.com',
            get_new_uptoken: false,
            auto_start: true,
            max_retries: 3,
            filters: {
                max_file_size: '10000mb',
                prevent_duplicates: false
                // Specify what files to browse for
                // mime_types: [
                //     {title : 'apk files', extensions : 'apk'} // 限定apk后缀上传格式上传
                // ]
            },
            init: {
                'FilesAdded': (up, files) => {
                    console.log('文件就绪', files);
                },
                BeforeUpload: (up, file) => {
                    console.log('上传之前', file);
                },
                UploadProgress: (up, file) => {
                    console.log('上传中 file', file);
                    this.progress = file.percent + '%';
                },
                FileUploaded: (up, file, info) => {
                    console.log('文件上传完毕');
                    var domain = up.getOption('domain');

                    var res = Qiniu.parseJSON(info);
                    var sourceLink = domain + "/" + res.key; // 获取上传成功后的文件的Url
                    // 图片未传到七牛云上面，所以获取链接不能显示图片
                    console.log(sourceLink);
                },
                Error: (up, err, errTip) => {
                    console.log('上传失败', err);
                },
                Key: (up, file) => { }
            }
        });
    }

    addImg($file) {
        this.$vm.current.$img2Url($file.name, 'file_url');
    }

    // 将markdown格式文章解析成html
    handleSave = (value) => {
        let html = marked(value);
        console.log(html);
    }

    componentDidMount() {
        this.initQiniu();
    }

    handleClick = () => {
        let html = marked(this.state.value);

        this.addArticle(this.state.title, html)
    }

    // 增加文章接口
    async addArticle(title, content) {
        const res = await _addArticle({
            title,
            content
        });

        console.log(res);

        if (res.data.code === 0) {
            setTimeout(() => {
                success()
                this.props.history.push(`/createQuestion`);
            }, 1000);
        }
    }

    render() {
        const { title } = this.props.match.params
        const { value } = this.state

        return (
            <Fragment>
                <BlogHeader activeIndex={1} />
                <TitleInput title={title} saveTitle={this.saveTitle} />
                <div style={{
                    height: 600,
                    width: 1200,
                    position: 'relative',
                    left: '50%',
                    marginLeft: -600
                }}>
                    <Editor
                        placeholder='编辑文章内容...'
                        ref={this.$vm}
                        value={value}
                        addImg={($file) => this.addImg($file)}
                        onChange={value => this.handleChange(value)}
                        onSave={(value) => this.handleSave(value)}
                    />
                </div>
                <div id="uploadImage">选择文件</div>
                <button class="submit" onClick={this.handleClick}>提交</button>
            </Fragment>
        )
    }
}

export default withRouter(EditArticlePage);